package com.cloudspace.jindun.manager;

import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

import com.cloudspace.jindun.JindunApp;
import com.cloudspace.jindun.constants.Constants;
import com.cloudspace.jindun.utils.AppPreferences;

import static com.cloudspace.jindun.constants.Constants.MESSAGE_BROADCAST;

/**
 * Created by zengxianhua on 17/3/27.
 */

public class MessageNumberManager {
    private static MessageNumberManager messageNumberManager;

    private MessageNumberManager(){}

    public static synchronized MessageNumberManager getInstance(){
        if (messageNumberManager == null){
            messageNumberManager = new MessageNumberManager();
        }

        return messageNumberManager;
    }

    public void addMessageUnread(String channelId){
        if (TextUtils.isEmpty(channelId)){
            return;
        }

        String channelSuffix =  getChannelSuffix(channelId);

        String unreadMessageIds = AppPreferences.getString(Constants.MESSAGE_UNREAD, "");

        if (TextUtils.isEmpty(unreadMessageIds)){
            unreadMessageIds = channelSuffix;
        }else if (!unreadMessageIds.contains(channelSuffix)){
            unreadMessageIds += channelSuffix;
        }else{
            return;
        }

        AppPreferences.putString(Constants.MESSAGE_UNREAD, unreadMessageIds);
        sendBroadCast();
    }

    public String getChannelSuffix(String channelId){
        if (TextUtils.isEmpty(channelId)){
            return "";
        }

        return channelId + ",";
    }

    public boolean isMessageUnread(){
        String unreadMessageIds = AppPreferences.getString(Constants.MESSAGE_UNREAD, "");
        return !TextUtils.isEmpty(unreadMessageIds);
    }

    public boolean isChannelUnread(String channelId){
        if (TextUtils.isEmpty(channelId)){
            return false;
        }

        String unreadMessageIds = AppPreferences.getString(Constants.MESSAGE_UNREAD, "");
        return unreadMessageIds.contains(getChannelSuffix(channelId));
    }

    public void readMessage(String channelId){
        if (TextUtils.isEmpty(channelId)){
            return;
        }

        String unreadMessageIds = AppPreferences.getString(Constants.MESSAGE_UNREAD, "");
        String channelSuffix = getChannelSuffix(channelId);
        unreadMessageIds = unreadMessageIds.replace(channelSuffix, "");
        AppPreferences.putString(Constants.MESSAGE_UNREAD, unreadMessageIds);

        sendBroadCast();
    }

    private void sendBroadCast() {
        LocalBroadcastManager.getInstance(JindunApp.getInstance()).sendBroadcast(new Intent(MESSAGE_BROADCAST));
    }

    public void clearAllMessage(){
        AppPreferences.putString(Constants.MESSAGE_UNREAD, "");
    }

}
